# SVN FILE: $Id$
#
# Project Name : 
#
# @package -.
# @author $Chirantan V. Rajhans$
# @copyright $Copyright:(c) 2008 .All Rights Reserved$
# @version $New$
# @lastrevision $Date$
# @modifiedby $LastChangedBy$
# @lastmodified $LastChangedDate$
# @filesource $E:/Rubyfun/MyStringAPI.rb$
#

require 'net/http'
require 'uri'

# *Description*
# * Class for Youtube related stuff
# *Exception*
# * No Exception
class Youtube
  # *Description*
  # * Initializes object of Youtube
  # *Parameters*
  # * None
  # *Returns*
  # * Object of class Youtube
  # *Exception*
  # * No Exception
  def initialize
    @video_id = ''
  end

  # *Description*
  # * initiates the download process of the video contained in the given url
  # *Parameters*
  # * url - URL of the page that contains the video
  # *Returns*
  # * -
  # *Exception*
  # * No Exception
  def download(url)
    rxp = Regexp.new('v=(.*)') unless url.match('&')
    rxp = Regexp.new('v=(.*)&') if url.match('&')
    video_id = url.scan(rxp)
    @video_id = video_id[0].to_s
    url = "http://www.youtube.com/v/" + @video_id
    p url
    find_t(url)
  end
  
  private 
  
  # *Description*
  # * Finds the value of t for the given video
  # *Parameters*
  # * url
  # *Returns*
  # * Object of class Youtube
  # *Exception*
  # * No Exception
  def find_t(url)
    res = get_request(url)
    case res
      when Net::HTTPRedirection then find_t(res['location'])
      when Net::HTTPSuccess then
        rxp = Regexp.new('&t=(.*)&use_get_video_info')
        t = url.scan(rxp)[0][0]
        get_video("http://www.youtube.com/get_video?video_id=#{@video_id}&t=#{t}")
    end
  end
  
  # *Description*
  # * Actually starts downloading the video using the obtained token,
  # *Parameters*
  # * url
  # *Returns*
  # * -
  # *Exception*
  # * No Exception
  def get_video(url)
    res = get_request(url)
    case res
      when Net::HTTPRedirection then get_video(res['location'])
      when Net::HTTPSuccess then
        File.open(@video_id.to_s + '.flv', File::WRONLY|File::CREAT|File::BINARY) do |f1|
          f1.puts res.body
        end
      end
  end

  # *Description*
  # * Sends a GET request to specified url
  # *Parameters*
  # * url - URL to which the request is to be sent
  # *Returns*
  # * response handle for the url
  # *Exception*
  # * No Exception
  def get_request(url)
    uri = URI.parse(url)
    req = Net::HTTP::Get.new(uri.path.to_s + '?' + uri.query.to_s)
    Net::HTTP.Proxy('ptproxy.persistent.co.in','8080','chirantan_rajhans','comeasyouare!23').start(uri.host, uri.port) {|http| http.request(req)}
  end  
end

Youtube.new.download('http://in.youtube.com/watch?v=AP5VIhbJwFs')
